// middleware.ts
import type {NextRequest} from 'next/server';
import {NextResponse} from 'next/server';
import {COOKIE_KEY} from "@/utils";

export function middleware(request: NextRequest) {
    const {pathname} = request.nextUrl

    console.log('middleware', pathname)
    // return NextResponse.next();

    // 假设你的登录状态存储在cookie中
    const isLoggedIn = request.cookies.get(COOKIE_KEY);

    // 如果没有登录，并且不是在登录页面
    if (!isLoggedIn && pathname !== '/login' && pathname !== '/login_redirect'
        && !pathname.startsWith('/_next/static')
        && !pathname.startsWith('/share')) {

        console.log('isLoggedIn', isLoggedIn, pathname)

        // 重定向到登录页面，并附加当前页面的URL作为`redirect`查询参数
        const returnUrl = encodeURIComponent(request.nextUrl.pathname + request.nextUrl.search);
        console.log('redirect to login with return URL', returnUrl);
        return NextResponse.redirect(new URL(`/login?returnUrl=${returnUrl}`, request.url));
    }

    // 如果已经登录，或者是访问登录页面，则正常继续
    return NextResponse.next();
}
